'use strict';

const { Op } = require('sequelize');
const { Service } = require('egg');

function toInt(str) {
    if (typeof str === 'number') return str;
    if (!str) return str;
    return parseInt(str, 10) || 0;
}

class ArticleService extends Service {
    async index() {
        const { ctx } = this;
        const { size, current } = ctx.query;
        const Article = ctx.model.Article;
        const limit = ctx.helper.getCurrent({ size, current });

        const query = {
            ...limit,
            where: {
                status: 1,
            },
        };

        const res = await Article.findAll(query);
        const count = await ctx.model.Article.count();

        return {
            count,
            data: res,
        };
    }

    async add() {
        const { ctx } = this;
        const { title, cover, content } = ctx.request.body;
        const Article = ctx.model.Article;
        const article = await Article.create({ title, cover, content });
        console.log(article);
        return {
            code: 0,
            data: null,
            message: '添加成功',
        };
    }

    async show() {
        const { ctx } = this;
        const { id } = ctx.query;
        const query = {
            where: {
                id: toInt(id),
                status: 1,
            },
        };
        const article = await ctx.model.Article.findOne(query);
        if (!article) {
            return {
                data: null,
                message: '无该数据',
                code: 1,
            };
        }
        return {
            data: article.dataValues,
        };
    }

    async edit() {
        const { ctx } = this;
        const { id, ...data } = ctx.request.body;

        const Article = ctx.model.Article;
        const article = await Article.findByPk(toInt(id));
        if (!article) {
            ctx.status = 404;
            return;
        }
        await article.update(data);
        return {
            data: null,
            message: '修改成功',
        };
    }

    async destroy() {
        const { ctx } = this;
        let { ids } = ctx.request.body;
        const Article = ctx.model.Article;

        if (!Array.isArray(ids)) {
            ids = [ids];
        }

        const articles = await Article.findAll({
            where: {
                id: ids.map(id => toInt(id))
            }
        });

        if (articles.length === 0) {
            return {
                data: null,
                message: '无该数据',
                code: 1,
            };
        }

        await Article.update({ status: 0 }, {
            where: {
                id: ids.map(id => toInt(id))
            }
        });

        return {
            data: null,
            message: '删除成功',
        };
    }

}

module.exports = ArticleService;
